<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\GoodsEorderInfo;
use App\Models\Goods;
use App\Commands\OperationLogCommand;
use App\Http\Requests\Admin\GoodsEorder\StoreRequest;
use App\Http\Requests\Admin\GoodsEorder\UpdateRequest;
use Illuminate\Support\Facades\Input;
use App\Services\CustomSearch;
use App\Services\QueryStock;

class GoodsEorderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $goodsEorderInfo = GoodsEorderInfo::orderBy('goods_id','desc');
        $checkStatus = ['ALL'=>'所有备案状态', '1'=>'未备案', '2'=>'已备案'];
        $filter = [
            'goods_sn' => trim($request->get('goods_sn')),
            'checkStatus' => trim($request->get('checkStatus')),
            'batchNumbers' => trim($request->get('batchNumbers')),
        ];
        //goods_id查询
        if ($filter['goods_sn']&&$filter['goods_sn']!=''){
            $goodsEorderInfo = $goodsEorderInfo->where('goods_sn','like','%'.$filter['goods_sn'].'%');
        }
        //批次号查询
        if ($filter['batchNumbers']&&$filter['batchNumbers']!=''){
            $goodsEorderInfo = $goodsEorderInfo->where('batchNumbers','like','%'.$filter['batchNumbers'].'%');
        }
        //审核状态查询
        if ($filter['checkStatus']&&$filter['checkStatus']!='ALL'){
            $goodsEorderInfo = $goodsEorderInfo->where('checkStatus', $filter['checkStatus']-1);
        }

        $goodsEorderInfo = $goodsEorderInfo->paginate(10);
        //dd($goodsEorderInfo);
        return view('admin.goods_e_order.index',compact('goodsEorderInfo','filter','checkStatus'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(GoodsEorderInfo $goodsEorderInfo)
    {

        return view('admin.goods_e_order.create',compact('goodsEorderInfo'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreRequest $request,GoodsEorderInfo $goodsEorderInfo)
    {
        $param = $request->all();
        $param['add_time'] = date('Y-m-d H:i:s');

        $egoodsArr = GoodsEorderInfo::lists('goods_sn')->toArray();
        $is_egoods = in_array($param['goods_sn'],$egoodsArr);
        if($is_egoods){
            return redirect::back()->withInput()->with('message','该货号已存在');
        }
        //dd($param);
        $goodsEorderInfo = $goodsEorderInfo->create($param);
        $this->dispatch(
            new OperationLogCommand('添加备案商品','GoodsEorderInfo','goods_id:'.$goodsEorderInfo->goods_id)
        );
        return Redirect('admin/goodsEorder');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $goodsEorderInfo = GoodsEorderInfo::find($id);
        return view('admin.goods_e_order.edit',compact('goodsEorderInfo'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateRequest $request, $id)
    {
        //dd($request->all());
        $goods_sn = $request->get('goods_sn');
        $goods_sn_input = Input::get('goods_sn');
        //dd($goods_sn_input);
        //if()
        //return Redirect('admin/goodsEorder')->back()->withInput()->withErrors('用户不存在');
        $goodsEorderInfo = GoodsEorderInfo::find($id);

        if (empty($request->unitCus2) || $request->unitCus2=='000'){
            $request['unitCus2'] = null;
        }

        if (empty($request->sec_proportion) || empty($request->unitCus2)){
            $request['sec_proportion'] = null;
        }

        $goodsEorderInfo->update($request->all());

        $this->dispatch(
            new OperationLogCommand('修改备案商品','GoodsEorderInfo','goods_id:'.$id)
        );

        return Redirect('admin/goodsEorder');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $goodsEorderInfo = GoodsEorderInfo::find($id);
        $goods = Goods::where('goods_sn',$goodsEorderInfo->goods_sn)->get()->toArray();
        //dd($goods);
        if($goods){
            $return['status']=0;
            $return['message']='该备案商品已使用，不能删除！';
        }else{
            $goodsEorderInfo->delete();
        }

        $this->dispatch(
            new OperationLogCommand('删除备案商品','GoodsEorderInfo','id:'.$id)
        );
        return $return;
    }

    public function toggleShow(){

        $id = Input::get("id");
        $checkStatus = GoodsEorderInfo::where("goods_id",$id)->pluck("checkStatus");
        $data = array();

        if($checkStatus==0){
            $data['checkStatus'] = 1;
            $data['goods_id'] = $id;
            $res = GoodsEorderInfo::where("goods_id",$id)->update(['checkStatus'=>1]);
        }else{
            $data['checkStatus'] = 0;
            $data['goods_id'] = $id;
            $res = GoodsEorderInfo::where("goods_id",$id)->update(['checkStatus'=>0]);
        }
        if($res != false){
            $data['info'] = true;
        }else{
            $data['info'] = false;
        }
        return $data;

    }


    /**
     * 根据商品编号查询商品在海关的备案信息
     * @param  [type] $goods_sn [商品编号、商品货号]
     * @return [type]           [description]
     */
    public function customSearch($goods_sn, CustomSearch $customSearch)
    {
        $goods_sn = trim($goods_sn);

        $result = $customSearch->sendPost($goods_sn);

        if (key_exists($goods_sn,$result)){

            $return = $result[$goods_sn];
        }else{

            $return = [];
        }

        return response()->json($return);
    }

    /**
     * 商品在公共仓的库存查询
     * @param  string $goods_sn [商品货号（编号）]
     * @return [type]           [description]
     */
    public function queryStock($goods_sn, QueryStock $queryStock)
    {

        $result_xml = $queryStock->sendPost($goods_sn);

        // $result = json_decode($result);

        /*echo '<BR>isSucc:'.$result->isSucc;
        echo '<BR>msg:'.$result->msg;
        echo '<BR>obj:'.$result->obj;*/

        $xml =simplexml_load_string($result_xml);
        $xmljson= json_encode($xml);
        $result=json_decode($xmljson,true);

        if (!empty($result['stock']['List'])){

            $return = $result['stock'];
        }else{

            $return = [];
        }

        return response()->json($return);

    }
}
